<?php
namespace User\Controller;
use Think\Controller;
use Think\Page;
use User\Controller\UserController;
use Common\Service\Sms\ShortMessageService;
use User\Model\FactoryModel;
use Wap\Model\PraiseItemModel;

class PraiseController extends UserController
{
    public function index()
    {
        $page = I("get.page", 1, ""); //1:默认从第一页开始读取
        $praiseName = I("get.praiseName", "", "");
        $where['token'] = $this->wxuser['token'];
        $where['status'] = array('NEQ', 9);
        if (!empty($praiseName)) {
            $where['title'] = array('LIKE', "%" . $praiseName . "%");
        }
        $limit = 10;
        $mode = D("praise");
        $count = $mode->where($where)->count();
        $page = new Page($count, $limit);
        $show = $page->show();
        $this->assign("page", $show);
        $datas = $mode->where($where)->order('id desc')->limit($page->firstRow . ',' . $page->listRows)->select();//TODO: should not be here


        $this->assign("datas", $datas);//模板变量
        $this->display("index");//模板地址
    }

    public function edit()//TODO:
    {
        $praise = array();
        //$keyword = array();

        $id = 0;
        if (IS_POST) {
            $id = I("POST.praise", 0, "");
            $praise = D("praise")->where(['id' => $id])->find();
        } else if (IS_GET) {
            $id = I("GET.praise", 0, "");
            $praise = D("praise")->where(['id' => $id])->find();
        }
        // $keyword = D( "keyword" )->where( "pid = %d", array( $id ) )->select();
        $this->assign("praise", $praise);
        // $this->assign( "keywords", $keyword );
        $this->display();
    }

    private function keyword_page()//not need any more
    {
        $praise = I("get.praise", array(-1), "");

        $page = I("get.page", 1, "");
        $limit = I("get.limit", 3, "");

        // $condition['pid'] = array( "not in", $praise );
        $condition['id'] = $praise;
        // $count = ceil( D( "keyword" )->where( $condition )->count() / $limit);
        // $datas = D( "keyword" )->where( $condition )->page( $page, $limit )->select();
        $keywords = D("praise")->where($condition)->getField("keyword");
        $keywords = explode(",", $keywords);
        $count = count($keywords);
        $datas = array_slice($keywords, 0, $limit);

        $obj = array(
            "count" => $count,//总共的页数
            "curren" => intval($page),//当前页
            "next" => intval($page) + 1,//TODO:cache 当前页
            "pre" => intval($page) - 1,//TODO:cache 前一页
            "size" => count($datas), //当前页数据个数
            "datas" => $datas//查询到的数据
        );
        return $obj;
    }

    public function keyword_add()
    {
        $pid = I("post.praise", -1, "");
        $data = array("pid" => $pid, "keyword" => I("post.keyword", "", ""), "token" => D("praise")->where("id = %d", array($id))->getField("token"));
        $added = D("keyword")->save($data);
        $result = array("added" => 0, "data" => array());

        if ($added === false) {
            $result['added'] = 0;
        } else if ($added <= 0) {
            $result['added'] = 0;
        } else if ($added > 0) {
            $allowed = array("id", "pid", "keyword");
            $result['added'] = $added;
            $result['data'] = D("keyword")->where("id = %d", array($added))->field($allowed)->find();
        }

        $this->ajaxReturn($result);
    }

    public function keyword_update()
    {
        $keyword = I("post.keywords", -1, "");
        $condition['id'] = $keyword;

        $updated = D("keywords")->where($condition)->save();
        $result = array('updated' => 0, 'data' => array());
        if ($updated === false) {
            $result['updated'] = 0;
        } else if ($updated === 0) {
            $result['updated'] = 0;
        } else if ($updated > 0) {
            $result['updated'] = 1;
        }

        $result['data'] = D("keywords")->field("field, keyword, pid")->where($condition)->find();

        return $this->ajaxReturn($result);
    }

    public function keyword_delete()
    {
        $keywords = I("post.keywords", array(-1), "");
        $condition['id'] = array("in", $keywords);

        $deleted = D("keywords")->where($condition)->delete();
        $result = array("deleted" => 0, 'page' => array());
        if ($deleted === false) {
            $result['deleted'] = 0;
        } else if ($deleted === 0) {
            $result['deleted'] = 0;
        } else if ($deleted > 0) {
            $result['deleted'] = $deleted;
        }

        $result['page'] = $this->keyword_page();

        $this->ajaxReturn($result);
    }

    public function keyword()
    {
        $page = $this->keyword_page();
        $this->ajaxReturn($page);
    }

    public function update_wxuser()//设置微信账号信息
    {
        $praise = I("post.praise", -1, "");
        $data = array("wxname" => "", 'wechat_type' => 1, "appid" => "", "appsecret" => "", "wxname" => "",
            "wxid" => "", "weixin" => "", "token" => "");

        $data = array_intersect_key($_POST, $data);
        $mode = D("wxuser");

        $added = null;
        $updated = null;
        $mode->startTrans();
        if ($praise != -1 && !empty($praise)) {
            $mode->create($data);//TODO: logic error;
            $added = $mode->add();//TODO: login bug, baddly;
        }

        if ($added != null && $added > 0) {
            $updated = D("praise")->where("id = %s", array($praise))->save(array("wxuser" => $added));//TODO:logic bug
        }

        if ($updated === false || $updated === 0 || $added <= 0) {
            $mode->rollback();
            return $this->ajaxReturn(array());
        }

        if ($updated > 0 && $added > 0) {
            $mode->commit();
            return $this->ajaxReturn($data);
        }

        if ($added == null) {
            return $this->ajaxReturn(array());
        }
    }

    public function update_praise()//设置活动信息
    {
        $id = I("post.id", -1, "");
        $data = array(
            "title" => "",
            "picurl" => "",
            "keyword" => "",
            "per_num" => -1,
            "per_num_sum" => -1,
            "sum_num" => -1,
            "limit_sum" => -1,
            "startdate" => "",
            "enddate" => "",
            "showpic" => 0,
            "type" => 'scene',
            "style" => 1
        );
        $data = array_intersect_key($_POST, $data);

        $data['startdate'] = strtotime($data['startdate']);
        $data['enddate'] = strtotime($data['enddate']);

        $data_info['info'] = $data['info'];
        $data_info['know'] = $data['keyword'];
        $data['info'] = json_encode($data_info, JSON_UNESCAPED_UNICODE);
        $img = $this->upload(";");
        if ($img) {
            $data['picurl'] = $img;
        }
        $mode = D("praise");
        if (!isset($data['type']) || (isset($data['type']) && empty($data['type']))) {
            $data['type'] = 'scene';
        }

        $result = null;

        if ($id != -1 && !empty($id)) {
            $data['id'] = $id;
            $result['id'] = $id;
            $praise_info = M("praise")->where(['id' => $id])->getField('info');
            if (!empty($praise_info)) {
                $praise_info = json_decode($praise_info, true);
                if (isset($praise_info['share_title'])) {
                    $data_info['share_tile'] = $praise_info['share_title'];
                }
                if (isset($praise_info['share_pic'])) {
                    $data_info['share_pic'] = $praise_info['share_pic'];
                }
                if (isset($praise_info['share_desc'])) {
                    $data_info['share_desc'] = $praise_info['share_desc'];
                }
            }
            $data['info'] = json_encode($data_info, JSON_UNESCAPED_UNICODE);
            unset($data['keyword']);
            $mode->create($data);
            $result['updated'] = $mode->save($data);
            $result['success'] = $result['updated'];
        } else {
            $data['keyword'] = date("Y-m-d H:i:s");
            $data['token'] = $this->wxuser['token'];
            $mode->create($data);
            unset($data['id']);
            $id = $mode->add($data);
            $praiseLink = "http://" . $_SERVER['SERVER_NAME'] . "/Wap/Praise/index/praise/" . $id;
            $mode->where(['id' => $id])->save(['link' => $praiseLink, 'id' => $id]);
            $result['id'] = $id;
            $result['added'] = $id ? true : false;
            $result['success'] = $id;
        }
        if ($result['success'] > 0 || ($result['success'] === 0 && $id > 0)) {
            header("Content-type: text/html; charset=utf-8");
            $this->redirect("User/Praise/edit", array("praise" => $id), 5, "保存成功,正在返回。。。");
        } else {
            $this->error("保存失败", 5);
        }
    }

    public function items()
    {
        $page = I("get.page", 1, ""); //1:默认从第一页开始读取
        $limit = 15;
        $praise_id = I("get.praise_id", "", "");
        $where['token'] = $this->wxuser['token'];
        $where['status'] = array('NEQ', 9);
        $praiseDatas = M("praise")->where($where)->select();
        $praise = array();
        if (empty($praise_id)) {
            $praise = M("praise")->where($where)->order('id desc')->find();
            $praise_id = $praise['id'];
        } else {
            $praise = M("praise")->where(['id' => $praise_id])->find();
        }
        $condition['praise_id'] = $praise_id;
        $condition['status'] = array('NEQ', -1);
        $itemName = I("get.itemName", "", "");
        if (!empty($itemName)) {
            $condition_ori['show_name'] = array("LIKE", "%" . $itemName . "%");
            $condition_ori['grade'] = $itemName;
            $condition_ori['_logic'] = 'OR';
            $condition['_complex'] = $condition_ori;
        }
        $mode = D("praise_item");
        $count = ceil($mode->where($condition)->count() / $limit);//TODO: should use cache
        $datas = $mode->where($condition)
            ->order("id desc")
            ->page($page, $limit)
            ->select();//TODO: should not be here

        $page = array(
            "count" => $count + 1,//总共的页数
            "curren" => $page,//当前页
            "next" => $page + 1,//TODO:cache 当前页
            "pre" => $page - 1,//TODO:cache 前一页
            "size" => $limit, //当前页数据个数
            //"datas"	=>	$datas//查询到的数据
        );
        $this->assign("page", $page);
        $this->assign("praiseid", $praise_id);
        $this->assign("praiseDatas", $praiseDatas);
        $this->assign("datas", $datas);
        $this->assign("praise", $praise);
        $this->display("items");
    }

    //投票项导出
    public function download()
    {
        $praise_id = I("get.praise_id", "", "");
        $praise = M("praise")->where(['id' => $praise_id])->find();

        $condition['praise_id'] = $praise_id;
        $condition['status'] = array('NEQ', -1);
        $mode = D("praise_item");
        $datas = $mode->where($condition)
            ->field('grade, show_name, contract, votes, pv')
            ->order("id desc")
            ->select();

        $zh_fields = array(
            "投票项",
            "名称",
            "简介",
            "结果",
            "浏览量"
        );
        $this->exportexcel($datas, $zh_fields, $praise['title'] . "投票项导出");
    }

    private function exportexcel($data = array(), $title = array(), $filename = 'report')
    {
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=" . $filename . ".xls");
        header("Pragma: no-cache");
        header("Expires: 0");
        //导出xls 开始
        if (!empty($title)) {
            foreach ($title as $k => $v) {
                $title[$k] = iconv("UTF-8", "GB2312", $v);
            }
            $title = implode("\t", $title);
            echo "$title\n";
        }
        if (!empty($data)) {
            foreach ($data as $key => $val) {
                foreach ($val as $ck => $cv) {
                    $data[$key][$ck] = iconv("UTF-8", "GB2312", "\"" . $cv . "\"");
                }
                $data[$key] = implode("\t", $data[$key]);
            }
            echo implode("\n", $data);
        }
    }

    public function records()
    {
        $where['item'] = I("get.item", "", "");
        $where['praise'] = I('get.praise', -1, '');
        $condition = array();

        $this->scopeRecord($condition, $where);
        $this->scopePraise($condition, $where);
        // $rows = D( "praise_record" )->where( $condition )->select();
        //
        $condition['praise'] = $condition['praise_id'];//TODO: 历史遗留问题

        $page = I("get.page", 1, ""); //1:默认从第一页开始读取
        $limit = 6;

        $mode = D("praise_record2");
        $count = $mode->where($condition)->count();//TODO: should use cache
        $page = new Page($count, 15);
        $show = $page->show();
        $datas = $mode->where($condition)->order('id desc')->limit($page->firstRow . "," . $page->listRows)->select();//TODO: should not be here

        $this->assign("page", $show);
        $this->assign("datas", $datas);
        $this->display("item_record");
    }

    public function record_delete()
    {
        $records = I("post.records", array(-1), "");
        $praise = I("post.praise", -1, "");
        $item = I("post.item", "", "");

        $condition['id'] = array("in", $records);

        $rows = D("praise_record2")->where($condition)->delete();
        if ($rows) {
            header("Content-type: text/html; charset=utf-8");
            $this->redirect('User/Praise/records', array("praise" => $praise, "item" => $item));
        } else {
            header("Content-type: text/html; charset=utf-8");
            $this->redirect('User/Praise/records', array("praise" => $praise, "item" => $item));
        }
    }

    public function item_edit()
    {
        $page = I("post.page", 1, "");
        $where['id'] = I("post.item_id", "", "");
        $data['praise_id'] = I('post.praise_id', '', '');
        $data['show_name'] = I('post.show_name', '', '');
        $data['contract'] = I('post.contract', '', '');
        $data['pic'] = $this->upload();
        $data['status'] = 1;
        $data['external_link'] = I('post.external_link', '', '');

        $data['yuliu'] = I('post.yuliu', '', '');
        if ($data['yuliu'] != '') {
            if ((substr($data['yuliu'], 0, 7) !== 'http://') && (substr($data['yuliu'], 0, 8) !== 'https://')) {
                $data['yuliu'] = "http://" . $data['yuliu'];
            }
        }
        $data['click'] = I('post.click', '', '');
        if (!empty($where['id'])) {
            $praise = M("praise_item")->where($where)->find();
            if (!empty($praise)) {
                M("praise_item")->where($where)->save($data);
            }
        } else {
            $cond['praise_id'] = $data['praise_id'];
            $cond['status'] = 1;
            $max_id = M("praise_item")
                ->field("max(grade) as grade")
                ->where($cond)
                ->find();
            if (empty($max_id['grade'])) {
                $data['grade'] = 1;
            } else {
                $data['grade'] = $max_id['grade'] + 1;
            }
            $data['add_time'] = time();
            M("praise_item")->add($data);
        }
        $this->redirect("/User/Praise/items", array("praise_id" => $data['praise_id'], "page" => $page));
    }

    public function item_update()
    {
        $keys = array('id' => '', 'teacher_telephone' => "", 'teacher_name' => "", 'pic' => "", 'contract' => '', 'support_team' => '',
            "show_name" => "", "author_name" => "", "grade" => "", "birth_time" => "", 'birth_file' => '',
            "school_name" => "", "address" => "", 'city' => '', 'region' => '', 'provience' => '', 'status' => '', 'yuliu' => '', 'yuliu2' => '');

        $item = I("post.item", -1, "");
        $where['praise'] = I('post.praise', -1, '');
        $condition = array();
        $this->scopePraise($condition, $where);
        // $mode = M( "show" );
        //$mode = new PraiseItemModel();
        $mode = D('Wap/PraiseItem');
        $data = array_intersect_key($_POST, $keys);
        $data['id'] = $item;
        $validated = $mode->create($data);
        if (!$validated) {
            header("Content-type: text/html; charset=utf-8");
            $this->redirect('/User/Praise/item_edit', array('item' => $item, 'praise' => $where['praise']), 5, '未保存成功，信息不合法, 正在返回中。。。');
        }

        $result = $mode->insert($data, $condition);
        if (!$result['success']) {
            $this->assign("data", $_POST);//表单数据
            $this->assign("error", $result['validate']);//验证错误
            header("Content-type: text/html; charset=utf-8");
            $this->redirect('/User/Praise/item_edit', array('item' => $item, 'praise' => $where['praise']), 5, iconv("utf-8", "utf-8", '保存失败，正在返回中。。。'));
        } else {
            $sms = new ShortMessageService();
            $passedOrNot = array('审核未通过，请登录投票系统查看原因', '审核中', '审核通过');
            $msg = sprintf("%s小朋友作品%s。作品投票即日开启，请关注“浙里舟山”微信号进行投票；审核通过之后即可投票。", $data['author_name'], $passedOrNot[$data['status'] + 1]);

            if (!empty($data['teacher_telephone'])) {
                $sended = $sms->sendMsgTo($data['teacher_telephone'], $msg);
            }
            $uid = D("customer")->where(array("id" => $data['id']))->getField("id");
            $telephone = D("customer")->where(array("id" => $uid))->getField("telephone");
            $sended = $sms->sendMsgTo($telephone, $msg);

            header("Content-type: text/html; charset=utf-8");
            $this->redirect('/User/Praise/item_edit', array('item' => $item, 'praise' => $where['praise']), 5, iconv("utf-8", "utf-8", '保存成功，正在返回中。。。'));
        }
    }

    public function delete()
    {
        $praises = I("post.praises", array(-1), "");
        $condition['id'] = array("in", $praises);
        $condition['token'] = $this->wxuser['token'];
        $result = D("praise")->where($condition)->delete();

        if ($result === false) {
            //SQL 操作失败
        } else if ($result === 0) {
            //没有删除
        } else if ($result > 0) {
            //删除成功
        }

        header("Content-type: text/html; charset=utf-8");
        $this->redirect("User/Praise/index");
    }

    public function item_get()
    {
        $where['id'] = I("get.id", array(-1), "");
        $item = M("praise_item")->where($where)->find();
        echo json_encode($item);
        return;
    }

    public function item_delete()
    {
        $item_id = I("get.item_id", array(-1), "");
        $item = M("praise_item")->where(['id' => $item_id])->find();
        if (!empty($item)) {
            $data['status'] = -1;
            M("praise_item")->where(['id' => $item_id])->save($data);
        }
    }

    public function item_pass()
    {
        $items = I("post.items", array(-1), "");
        $where['praise'] = I('post.praise', -1, '');
        // $praise = I( "post.praise", array( -1 ), "" );
        $data['status'] = 1;
        $condition['id'] = array("in", $items);
        $this->scopePraise($condition, $where);

        $result = D('praise_item')->where($condition)->save($data);
        if ($result) {
            $sms = new ShortMessageService();
            foreach ($items as $item) {
                $res = D("praise_item")->join("LEFT JOIN esm_customer ON esm_customer.id = esm_praise_item.uid")->field("esm_praise_item.author_name, esm_customer.telephone, esm_praise_item.teacher_telephone")->where(array("esm_praise_item.id" => $item))->find();
                //$praise_item = D( "praise_item" )->where( array( "id" => $item ) )->getField( "uid", "teacher_telephone", "author_name" );
                //$telephone = D( "customer" )->where( array( "id" => $praise_item['uid'] ) )->getField( "telephone" );

                //$msg = sprintf("%s小朋友作品审核通过。作品投票将于2015年10月28日开始，届时请关注“浙报公益”微信号进行投票。", $data['author_name'] );

                $msg = sprintf("%s小朋友作品审核已通过。即日起可在“浙里舟山”微信号内为孩子点赞哦。", $res['author_name']);
                if (isset($res['telephone'])) {
                    //$msg = sprintf("%s小朋友作品审核已通过。10月29日后要在浙报公益微信平台为孩子点赞哦。", $res['author_name'] );
                    $sended = $sms->sendMsgTo($res['telephone'], $msg);
                }
                if (isset($res['teacher_telephone'])) {
                    //$msg = sprintf("%s小朋友作品审核通过。作品投票将于2015年10月28日开始，届时请关注“浙报公益”微信号进行投票。", $res['author_name'] );
                    $sended = $sms->sendMsgTo($res['teacher_telephone'], $msg);
                }
            }
            //$this->success( "保存成功", "/User/Praise/items", 5 );
            $this->success("保存成功", U("User/Praise/items", $_POST), 5);
        } else {
            //$this->error( "保存失败", "/User/Praise/items", 5 );
            $this->error("保存失败", U('User/Praise/items', $_POST), 5);
        }
    }

    public function item_nopass()
    {
        $items = I("post.items", array(-1), "");
        $where['praise'] = I('post.praise', -1, '');
        $condition['id'] = array("in", $items);
        $this->scopePraise($condition, $where);
        $data['status'] = -1;
        $model = D("praise_item");
        $result = $model->where($condition)->save($data);
        if ($result) {
            $sms = new ShortMessageService();
            foreach ($items as $item) {
                //$praise_item = D( "praise_item" )->where( array( "id" => $item ) )->getField( "uid", "teacher_telephone", "author_name" );
                //$telephone = D( "customer" )->where( array( "id" => $praise_item['uid'] ) )->getField( "telephone" );

                $res = D("praise_item")->join("LEFT JOIN esm_customer ON esm_customer.id = esm_praise_item.uid")->field("esm_praise_item.author_name, esm_customer.telephone, esm_praise_item.teacher_telephone")->where(array("esm_praise_item.id" => $item))->find();
                $msg = sprintf("很抱歉,%s小朋友作品审核未通过，请登录投票系统查看原因吧。", $data['author_name']);
                if (isset($res['telephone'])) {
                    //$msg = sprintf("%s小朋友作品审核未通过，请登录投票系统查看原因。作品投票将于2015年10月28日开始，届时请关注“浙报公益”微信号进行投票。", $res['author_name'] );
                    $sended = $sms->sendMsgTo($res['telephone'], $msg);
                }
                if (isset($res['teacher_telephone'])) {
                    //$msg = sprintf("%s小朋友作品审核未通过，请登录投票系统查看原因。作品投票将于2015年10月28日开始，届时请关注“浙报公益”微信号进行投票。", $res['author_name'] );
                    $sended = $sms->sendMsgTo($res['teacher_telephone'], $msg);
                }
                //$sms->sendMsgTo( $praise_item['teacher_telephone'], $msg );
                //$sms->sendMsgTo( $telephone, $msg );
            }
            //$this->success( "更新成功", "/User/Praise/items", 5 );
            $this->success("更新成功", U('User/Praise/items', $_POST), 5);
        } else {
            //$this->error( "更新失败", "/User/Praise/items", 5 );
            $this->error("更新失败", U('/User/Praise/items', $_POST), 5);
        }
    }

    private function scopeOrder($where)
    {
        $by = "";
        if (intval($where['order']) === 2) {
            $by = "votes desc";
        } else {
            $by = "add_time desc";
        }
        return $by;
    }

    private function scopeAuthorName(&$condition = array(), $where)
    {
        //$condition['author_name'] = $where['author_name'];
        if (!empty($where['author_name'])) {
            $condition['author_name'] = array('LIKE', "%" . trim($where['author_name']) . "%");
        }
        return $condition;
    }

    private function scopePraise(&$condition = array(), $where)
    {
        $ids = D('praise')->where(array('token' => $this->wxuser['token']))->select();
        if ($where['praise'] > 0) {
            $condition['praise_id'] = $where['praise'];
        } else if ($ids && (sizeof($ids) > 0)) {
            $cond = [];
            foreach ($ids as $id) {
                $cond[] = $id['id'];
            }
            $condition['praise_id'] = array('in', $cond);
        } else {
            $condition['praise_id'] = -1;
        }
        return $condition;
    }

    private function scopePraises()
    {
        $condition['token'] = $this->wxuser['token'];
        $datas = D("praise")->where($condition)->getField("id, title");
        return $datas;
    }

    private function scopeTelephone(&$condition = array(), $where)
    {
        if (!empty($where['telephone'])) {
            //$condition = $condition." telephone = %s ";
            $_complex['telephone'] = array("LIKE", "%" . $where['telephone'] . "%");//
            $_complex['teacher_telephone'] = array("LIKE", "%" . $where['telephone'] . "%");//
            $_complex['_logic'] = 'or';
            $condition['_complex'] = $_complex;
        }
        //return $condition;
    }

    private function scopeRegion(&$condition, $where)
    {
        if (!empty($where['region'])) {
            $condition['region'] = $where['region'];
        }
        //return $condition;
    }

    /*private function scopeSupportTeam( &$condition, $where )
    {
        if( !empty( $where['support_team'] ) ){
            $condition['support_team'] = $where['support_team'];
        }
        //return $condition;
    }*/

    private function scopeStatus(&$condition, $where)
    {
        if ($where['status'] < -1 || $where['status'] > 2) {
            $condition['status'] = array(array('gt', -2), array('lt', 2));
        } else {
            $condition['status'] = $where['status'];
        }
    }

    private function scopeItem(&$condition, $where)
    {
        if (empty($where['item'])) {
            $condition = array();
        } else {
            $condition['id'] = $where['item'];
        }
    }

    private function scopeRecord(&$condition, $where)
    {
        if (empty($where['item'])) {
            $condition = array();
        } else {
            $condition['pid'] = $where['item'];
        }
    }

    private function scopeSupportTeam(&$condition, $where)
    {
        if ($where['support_team'] < 0) {
            $condition['support_team'] = array('egt', $where['support_team']);
        } else {
            $condition['support_team'] = $where['support_team'];
        }
    }

    private function upload($addSign = '')
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = './Public/Uploads/praise/'; // 设置附件上传根目录
        $upload->subName = array("date", "Ymd");
        $upload->saveName = array("uniqid", "praise");
        // 上传文件
        $info = $upload->upload();
        $img = "";
        $picurl = I("post.picurl", "", "");
        if (!empty($picurl)) {
            $img .= $picurl . $addSign;
        }
        $picurl1 = I("post.picurl1", "", "");
        if (!empty($picurl1)) {
            $img .= $picurl1 . $addSign;
        }
        $picurl2 = I("post.picurl2", "", "");
        if (!empty($picurl2)) {
            $img .= $picurl2 . $addSign;
        }
        //if(!$info) {// 上传错误提示错误信息
        //$this->error($upload->getError());
        //}else{// 上传成功
        if ($info) {
            //$file =
            //$this->ajaxReturn( $info );
            //$temq	=	explode( "./", $file['savepath'], 2 );
            if (sizeof($info) == 1) {
                foreach ($info as $file) {
                    $img .= "http://" . $_SERVER["HTTP_HOST"] . '/Public/Uploads/praise/' . date('Ymd') . "/" . $file['savename'] . $addSign;
                }
            } else {
                foreach ($info as $file) {
                    $img = $img . "http://" . $_SERVER["HTTP_HOST"] . '/Public/Uploads/praise/' . date('Ymd') . "/" . $file['savename'] . $addSign;
                }
            }
        } else {
            //$this->ajaxReturn( $upload->getError() );
        }
        //$this->success('上传成功！');
        //}
        return $img;
    }

    //--活动发布--
    public function setPublish()
    {
        $praiseid = I("get.praise", array(-1), "");
        $praise = M("praise")->where(['id' => $praiseid])->find();
        if (!empty($praise)) {
            $data['status'] = 0;
            M("praise")->where(['id' => $praiseid])->save($data);
        }
        return $this->redirect("/User/Praise/index");
    }

    //--活动停用发布--
    public function setStop()
    {
        $praiseid = I("get.praise", array(-1), "");
        $praise = M("praise")->where(['id' => $praiseid])->find();
        if (!empty($praise)) {
            $data['status'] = 1;
            M("praise")->where(['id' => $praiseid])->save($data);
        }
        return $this->redirect("/User/Praise/index");
    }

    //--活动删除--
    public function setDelete()
    {
        $praiseid = I("get.praise", array(-1), "");
        $praise = M("praise")->where(['id' => $praiseid])->find();
        if (!empty($praise)) {
            $data['status'] = 9;
            M("praise")->where(['id' => $praiseid])->save($data);
        }
        return $this->redirect("/User/Praise/index");
    }

    private function getpage($count, $pagesize = 10)
    {
        $p = new Page($count, $pagesize);
        $p->setConfig('header', '<li class="rows">共<b>%TOTAL_ROW%</b>条记录&nbsp;第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页</li>');
        $p->setConfig('prev', '上一页');
        $p->setConfig('next', '下一页');
        $p->setConfig('last', '末页');
        $p->setConfig('first', '首页');
        $p->setConfig('theme', '%FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%%HEADER%');
        $p->lastSuffix = false;//最后一页不显示为总页数
        return $p;
    }

    public function share()
    {
        $params = I('post.', '', '');
        if (empty($params)) {
            $id = I('get.id', '', '');
            if (empty($id)) {
                return $this->redirect('/User/Praise/index');
            }
            $praise = M("praise")->where(['id' => $id])->find();
            if (empty($praise)) {
                return $this->redirect('/User/Praise/index');
            }
            $this->assign('praise', $praise);
            return $this->display();
        } else {
            if (!empty($params['id'])) {
                $data_info['share_title'] = $params['share_title'];
                $data_info['share_desc'] = $params['share_desc'];
                $praise_info = M("praise")->where(['id' => $params['id']])->getField('info');
                if (!empty($praise_info)) {
                    $praise_info = json_decode($praise_info, true);
                    if (isset($praise_info['info'])) {
                        $data_info['info'] = $praise_info['info'];
                    }
                    if (isset($praise_info['know'])) {
                        $data_info['know'] = $praise_info['know'];
                    }
                    if (isset($praise_info['share_pic'])) {
                        $data_info['share_pic'] = $praise_info['share_pic'];
                    }
                }
                $img = $params['share_pic'];
                if (!empty($img)) {
                    $ajaxImg = FactoryModel::ajaxImgUpload($img, "praise");
                    if ($ajaxImg['code'] != 1) {
                        return $this->my_error('图片上传失败');
                    }
                    $data_info['share_pic'] = $ajaxImg['msg'];
                }
                $data['info'] = json_encode($data_info);
                M("praise")->where(['id' => $params['id']])->save($data);
            }

            return $this->my_success("成功");
        }
    }

    public function desc()
    {
        $params = I('post.', '', '');
        if (empty($params)) {
            $id = I('get.id', '', '');
            if (empty($id)) {
                return $this->redirect('/User/Praise/index');
            }
            $praise = M("praise")->where(['id' => $id])->find();
            if (empty($praise)) {
                return $this->redirect('/User/Praise/index');
            }
            $this->assign('praise', $praise);
            return $this->display();
        } else {
            if (!empty($params['id'])) {
                $data['link'] = json_encode(array('desc' => $params['editorValue']));
                M("praise")->where(['id' => $params['id']])->save($data);
                return $this->redirect('/User/Praise/desc/?id=' . $params['id']);
            }
            return $this->redirect('/User/Praise/index');
        }
    }

    //-------投票项投票数清零------
    public function item_clear()
    {
        $praise_id = I("get.id", "", "");
        $item_id = I("get.item_id", "", "");
        if (!empty($praise_id)) {
            $cond['praise_id'] = $praise_id;
            $data['votes'] = 0;
            M("praise_item")->where($cond)->save($data);
        }elseif (!empty($item_id)){
            $cond['id'] = $praise_id;
            $data['votes'] = 0;
            M("praise_item")->where($cond)->save($data);
        }
    }
}

?>
